package net.entelijan.cobean.examples.util;

import java.util.List;

public class RoundaboutIterator<T> {

	private List<T> content;

	private int currentIndex;

	private int size;

	public RoundaboutIterator(List<T> content) {
		this.content = content;
		this.size = content.size();
		this.currentIndex = -1;
	}

	public T next() {
		T re;
		int cnt = 0;
		do {
			re = nextInternal();
			if (++cnt >= size) {
				throw new IllegalStateException(
						"Cannot support lists with only null values");
			}
		} while (re == null);
		return re;
	}

	private T nextInternal() {
		if (currentIndex < 0) {
			this.currentIndex = 0;
		} else {
			currentIndex++;
			currentIndex %= size;
		}
		T re = content.get(currentIndex);
		return re;
	}

	public T previus() {
		T re;
		int cnt = 0;
		do {
			re = prevInternal();
			if (++cnt >= size) {
				throw new IllegalStateException(
						"Cannot support lists with only null values");
			}
		} while (re == null);
		return re;
	}

	private T prevInternal() {
		if (currentIndex < 0) {
			this.currentIndex = size - 1;
		} else {
			this.currentIndex--;
			if (this.currentIndex < 0) {
				currentIndex = size - 1;
			}
		}
		T re = content.get(currentIndex);
		return re;
	}

	public List<T> getContent() {
		return this.content;
	}

}
